//
//  LastSearchViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/30.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "LastSearchViewController.h"
#import "GW_TextField.h"
#import "HomeViewController.h"
#import "HomeCityCollectionViewCell.h"
@interface LastSearchViewController ()<UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) GW_TextField *searchTextField;//自定义UITextfield目的是调整占位符位置
@property (nonatomic, strong) UIView *aView; //这个view的作用是使搜索的图片的占位符 调整位置
@property (nonatomic, strong) UIImageView *search; // 导航条 textfield内的搜索图标
@property (nonatomic, strong) UIButton *searchBtn; // 导航条右边 搜索按钮

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) NSMutableArray *historyArray;
@property (nonatomic, copy) NSString *string;
@end

@implementation LastSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configNavigation];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 64 + 22, 100, 17)];
    label.text = @"热门搜索";
    label.textColor = ColorFrom16(0x7F7E7D);
    label.font = PFRFONT(12);
    [self.view addSubview:label];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = ColorWhite;
    [_collectionView registerClass:[HomeCityCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(10);
        make.left.and.right.equalTo(self.view);
        make.height.equalTo(@142);
    }];
    
    UILabel *historyLabel = [UILabel new];
    historyLabel.text = @"搜索历史";
    historyLabel.textColor = ColorFrom16(0x7F7E7D);
    historyLabel.font = PFRFONT(12);
    [self.view addSubview:historyLabel];
    [historyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_collectionView.mas_bottom).offset(22);
        make.left.equalTo(self.view).offset(10);
        make.width.equalTo(@51);
        make.height.equalTo(@17);
    }];
    
    _tableview = [UITableView new];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.rowHeight = 40;
    _tableview.sectionFooterHeight = 40;
    UIButton *clearHistoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearHistoryBtn setTitle:@"清除历史搜索记录" forState:0];
    [clearHistoryBtn setTitleColor:ColorFrom16(0xA7A7A7) forState:0];
    clearHistoryBtn.titleLabel.font = PFRFONT(14);
    clearHistoryBtn.frame = CGRectMake(0, 0, GWIDTH, 40);
    
    [clearHistoryBtn addTarget:self action:@selector(actionClear) forControlEvents:UIControlEventTouchUpInside];
    _tableview.tableFooterView = clearHistoryBtn;
    [self.view addSubview:_tableview];
    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(historyLabel.mas_bottom).offset(10);
        make.left.and.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self startNetwork];
}

- (void)startNetwork
{
    //热门搜索
    _datasource = [NSMutableArray arrayWithCapacity:0];
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/goods/getHotSearch", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"%@", resultDict);
        NSArray *array = resultDict[@"data"];
        for (NSDictionary *dict in array) {
            [_datasource addObject:dict[@"name"]];
        }
        [_collectionView reloadData];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
    
    
    _historyArray = [NSMutableArray arrayWithCapacity:0];
    //搜索历史
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/goods/getHistory", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSArray *array = resultDict[@"data"];
        for (NSDictionary *dic in array) {
            [_historyArray addObject:dic[@"key"]];
        }
        [_tableview reloadData];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
}

//清除搜索历史记录
- (void)actionClear
{
    [self.historyArray removeAllObjects];
    [_tableview reloadData];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _datasource.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(IS_IPHONE5)
        return CGSizeMake((GWIDTH) / 3 - 20, 32);
    else if (IS_IPHONE_PLUS)
        return CGSizeMake(GWIDTH / 3 - 20, 32);
    else
        return CGSizeMake(GWIDTH / 3 - 15, 32);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    if(IS_IPHONE5)
        return UIEdgeInsetsMake(0, 20, 0, 18);
    else if (IS_IPHONE_PLUS)
        return UIEdgeInsetsMake(0, 20, 0, 20);
    else
        return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeCityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.label.text = _datasource[indexPath.row];
    
    _string = [[NSUserDefaults standardUserDefaults] objectForKey:@"select"];
        if ([cell.label.text isEqualToString:_string]) {
            cell.label.backgroundColor = ColorFrom16(0xFFE282);
        }else{
            cell.label.backgroundColor = ColorFrom16(0xffffff);;
        }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _string = _datasource[indexPath.row];
    @weakobj(self);
    if(_getKeyblock)
    {
        @strongobj(self);
        self.getKeyblock(self.string);
        [self.navigationController popViewControllerAnimated:YES];
    }
    [[NSUserDefaults standardUserDefaults] setObject:_string forKey:@"select"];
    [_collectionView reloadData];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _historyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = _historyArray[indexPath.row];
    cell.textLabel.textColor = ColorFrom16(0x757982);
    cell.textLabel.font = PFRFONT(14);
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.string = self.historyArray[indexPath.row];
    @weakobj(self);
    if(_getKeyblock)
    {
        @strongobj(self);
        self.getKeyblock(self.string);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //让cell的分割线距左侧的距离为0
    [cell setSeparatorInset:UIEdgeInsetsZero];
    [cell setLayoutMargins:UIEdgeInsetsZero];
}

- (void)configNavigation
{
    self.view.backgroundColor = ColorWhite;
    UIView *navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, 64)];
    navigationView.backgroundColor = ColorWhite;
    [self.view addSubview:navigationView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:IMAGE(@"nav_back@2x") forState:0];
    backBtn.frame = CGRectMake(10, 30, 20, 20) ;
    [backBtn addTarget:self action:@selector(handleBackBtn) forControlEvents:UIControlEventTouchUpInside];
    [navigationView addSubview:backBtn];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(GWIDTH - 60, 30, 40, 20) ;
    [searchBtn setTitle:@"搜索" forState:0];
    [searchBtn addTarget:self action:@selector(handleSearchBtn:) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn setTitleColor:ColorFrom16(0x4a4a4a) forState:0];
    [navigationView addSubview:searchBtn];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, GWIDTH, 1)];
    view.backgroundColor = ColorFrom16(0xe2e2e2);
    [self.view addSubview:view];
    
    
    _searchTextField = [[GW_TextField alloc]initWithFrame:CGRectMake(60, 24, GWIDTH - 90 - 44, 30)];
    _searchTextField.delegate = self;
    _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchTextField.placeholder = @"可输入店铺名、分类";
    [_searchTextField setValue:ColorFrom16A(0x999999, 0.57) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
    [_searchTextField setValue:PFRFONT(12) forKeyPath:@"_placeholderLabel.font"];
    _searchTextField.layer.backgroundColor = ColorFrom16(0xF0F0F0).CGColor;
    _searchTextField.layer.cornerRadius = 15;
    //这个view的作用是使搜索的图片的占位符 调整位置
    _aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    _aView.backgroundColor = ColorClear;
    _search = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_search_default"]];
    _search.frame = CGRectMake(0, 0, 16, 16);
    _search.center = _aView.center;
    [_aView addSubview:_search];
    _searchTextField.leftView = _aView;
    _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    [navigationView addSubview:_searchTextField];
}

- (void)handleBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handleSearchBtn:(UIButton *)sender
{
    @weakobj(self);
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/goods/setHistory?key=%@", GW_Domain, _searchTextField.text] parameters:@{@"key":_searchTextField.text} completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"搜索 %@", resultDict);
        if(self.getKeyblock)
        {
            @strongobj(self);
            self.getKeyblock(STRING(_searchTextField.text));
            [self.navigationController popViewControllerAnimated:YES];
        }
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
